package com.haohan.cloud.scm.goods.api.ctrl;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.common.tree.TreeUtil;
import com.haohan.cloud.scm.api.goods.entity.GoodsCategory;
import com.haohan.cloud.scm.api.goods.req.manage.EditGoodsCategoryReq;
import com.haohan.cloud.scm.common.tools.constant.FirstGroup;
import com.haohan.cloud.scm.common.tools.constant.SecondGroup;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.goods.core.GoodsCategoryCoreService;
import com.haohan.cloud.scm.goods.service.GoodsCategoryService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author dy
 * @date 2020/4/7
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/goods/category")
@Api(value = "ApiGoodsCategory", tags = "goodsCategory商品分类")
public class GoodsCategoryApiCtrl {

    private final GoodsCategoryCoreService categoryCoreService;
    private final GoodsCategoryService goodsCategoryService;

    @SysLog("新增商品分类")
    @PreAuthorize("@pms.hasPermission('scm_goodscategory_add')")
    @PostMapping
    @ApiOperation(value = "新增商品分类")
    public R<Boolean> addCategory(@Validated(FirstGroup.class) EditGoodsCategoryReq req) {
        GoodsCategory category = req.transTo();
        category.setId(null);
        return RUtil.success(categoryCoreService.addCategory(category));
    }

    @SysLog("修改商品分类")
    @PreAuthorize("@pms.hasPermission('scm_goodscategory_edit')")
    @PutMapping
    @ApiOperation(value = "修改商品分类")
    public R<Boolean> modifyCategory(@Validated(SecondGroup.class) EditGoodsCategoryReq req) {
        return RUtil.success(categoryCoreService.modifyCategory(req.transTo()));
    }

    @SysLog("删除商品分类")
    @PreAuthorize("@pms.hasPermission('scm_goodscategory_del')")
    @DeleteMapping("/{categoryId}")
    @ApiOperation(value = "删除分类")
    public R<Boolean> deleteCategory(@PathVariable("categoryId") String categoryId) {
        return RUtil.success(categoryCoreService.deleteById(categoryId));
    }

    @GetMapping("/{categoryId}")
    @ApiOperation(value = "查询商品分类详情")
    public R getById(@PathVariable("categoryId") String categoryId) {
        return RUtil.success(categoryCoreService.fetchInfo(categoryId));
    }

    @SysLog("当前租户下所有商品分类层级关系更新")
    @PostMapping("/allRelation")
    @ApiOperation(value = "当前租户下所有商品分类层级关系更新")
    public R<Boolean> allRelation(String rootId) {
        if (!StrUtil.equals(rootId, TreeUtil.ROOT)) {
            return R.failed("无权操作");
        }
        return RUtil.success(goodsCategoryService.updateAllRelation());
    }


}
